package com.recive.sbus.test.lock;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TryLock {
	private ArrayList<Integer> arrayList = new ArrayList<Integer>();
	private Lock lock = new ReentrantLock(); // 注意这个地方

	public static void main(String[] args) {
		final TryLock test = new TryLock();

		for (int i = 0; i < 10; i++) {
			new Thread() {
				public void run() {
					test.insert(Thread.currentThread());
				};
			}.start();
		}

	}

	public void insert(Thread thread) {
		if (lock.tryLock()) {
			try {
				System.out.println(thread.getName() + "得到了锁");
				for (int i = 0; i < 5; i++) {
					arrayList.add(i);
				}
				Thread.sleep(10000);
				System.out.println(thread.getName() + "sleep 10s");
			} catch (Exception e) {
				// TODO: handle exception
			} finally {
				System.out.println(thread.getName() + "释放了锁");
				lock.unlock();
			}
		} else {
			System.out.println(thread.getName() + "获取锁失败");
		}
	}
}